import platform
import json
import os
import argparse
from utils.logHelper import *
from utils.zipHelper import *

try: 
    logger = logHelper().logger
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--version', '-v', action='version',
                    version='%(prog)s version: 0.01',
                    help='show the version')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-b', '--backup', action='store_true')
    group.add_argument('-r', '--restore', action='store_true')
    parser.add_argument('path', type=str)
    args = parser.parse_args()
    logger.debug('args:{}'.format(args))

    if os.path.isdir(args.__dict__['path']) == False:
        logger.debug('backup option, the path should be valid directory')
        exit()


    logger.debug('current platform is {}'.format(platform.system()))
    system = 'unknown'
    if platform.system() == 'Darwin':
        system = 'mac'
    elif platform.system() == 'Windows':
        system = 'windows'
    else:
        logger.debug('only support mac and windows')
        exit()
        
    with open('./config.json','r',encoding='utf8') as fp:
        apps = json.load(fp)
        logger.debug('apps:{}'.format(apps))
        for app in apps:
            if args.__dict__['backup'] == True:
                target = os.path.join(args.__dict__['path'], app['name']+'.zip')
                logger.debug('app:{} version:{} path:{} target:{}'.format(app['name'], app['version'], app[system], target))          
                zipHelper.zipDir(app[system], target)
            elif args.__dict__['restore'] == True:
                zipFile = os.path.join(args.__dict__['path'], app['name']+'.zip')
                zipHelper.unzipDir(zipFile, app[system])
                pass

except KeyboardInterrupt:
    logger.debug('Program end, KeyboardInterrupt:')
except Exception as e:
    logger.debug('Program end, exception: {}'.format(str(e)))
finally:
    logger.info('program exit')
    exit() 